package com.example.myapplication;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.model.MedicalRecordFetcher;
import com.example.myapplication.model.PrescriptionFetcher;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class SearchActivity extends AppCompatActivity {
    EditText editText;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        editText = findViewById(R.id.editTextPhoneNumber);

        ImageView imageView_arrow = findViewById(R.id.imageView_arrow);
        imageView_arrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LinearLayout layout = findViewById(R.id.container_layout);
                layout.removeAllViews();
                String data = editText.getText().toString();
                new FetchMedicalRecordsTask().execute(data);
            }
        });
    }

    @SuppressLint("StaticFieldLeak")
    private class FetchMedicalRecordsTask extends AsyncTask<String, Void, List<List<Object>>> {

        @Override
        protected List<List<Object>> doInBackground(String... phoneNumbers) {
            String phoneNumber = phoneNumbers[0];
            return PrescriptionFetcher.getMedicalRecords(phoneNumber);
        }

        @Override
        protected void onPostExecute(List<List<Object>> medicalRecords) {
            super.onPostExecute(medicalRecords);
            if (medicalRecords != null) {
                try {
                    updateUI(medicalRecords);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private void updateUI(List<List<Object>> medicalRecords) throws ParseException {
        LinearLayout layout = findViewById(R.id.container_layout);
        LayoutInflater inflater = LayoutInflater.from(this);

        for (List<Object> record : medicalRecords) {
            RelativeLayout relativeLayout = (RelativeLayout) inflater.inflate(R.layout.relative_layout_prescription, layout, false);

            TextView textViewCaseNumber = relativeLayout.findViewById(R.id.textViewCaseNumber);
            TextView textViewCreationDate = relativeLayout.findViewById(R.id.textViewCreationDate);

            String symptom = (String) record.get(1);
            String prescription = (String) record.get(2);
            String usage = (String) record.get(3);

            textViewCaseNumber.setText(symptom);

            relativeLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(SearchActivity.this);
                    LayoutInflater inflater = SearchActivity.this.getLayoutInflater();

                    View dialogView = inflater.inflate(R.layout.dialog_layout, null);

                    TextView textViewSymptoms = dialogView.findViewById(R.id.textViewSymptoms);
                    TextView textViewPrescription = dialogView.findViewById(R.id.textViewPrescription);
                    TextView textViewCreationTime = dialogView.findViewById(R.id.textViewCreationTime);

                    textViewSymptoms.setText("症状：" + symptom);
                    textViewPrescription.setText("中药处方：" + prescription);
                    textViewCreationTime.setText("服用方式：" + usage);

                    builder.setView(dialogView)
                            .setTitle("处方详情")
                            .setNegativeButton("添加", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    SharedPreferences sharedPreferences = getSharedPreferences("my_preferences", Context.MODE_PRIVATE);
                                    String username = sharedPreferences.getString("user", "Default");
                                    String sql = "http://39.107.92.86:5000/add?phone_number=" + username +
                                            "&symptom=" + symptom + "&prescription=" + prescription + "&usage=" + usage;
                                    new UpdateProfileTask().execute(sql);
                                }
                            })
                            .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                    AlertDialog dialog = builder.create();
                    dialog.show();
                }
            });

            layout.addView(relativeLayout);
        }
    }

    private class UpdateProfileTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            String urlString = params[0];
            String result = "";

            try {
                URL url = new URL(urlString);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
                reader.close();
                result = sb.toString();

                urlConnection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
                result = "Error: " + e.getMessage();
            }

            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                boolean success = jsonObject.optBoolean("success");

                if (success) {
                    Toast.makeText(SearchActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(SearchActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(SearchActivity.this, "解析错误", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
